//
//  YWDetectAndUpkeepReplyTableViewController.m
//  maintain
//
//  Created by Kyo on 16/10/27.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDetectAndUpkeepReplyTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "UIView+Extension.h"

#import "UITableView+FDTemplateLayoutCell.h"
#import "YWDetailWorkTableViewCell.h"
#import "YWNewCommentCell.h"

#import "YWMission.h"
#import "YWHandler.h"

#import "YWReplyManager.h"
//#import "YWSelectContactTableViewController.h"
#import "YWSelectAtUserTableViewController.h"
#import "YWObserverTableViewController.h"

@interface YWDetectAndUpkeepReplyTableViewController ()<YWSelectAtUserTableViewDelegate,UITextFieldDelegate>{
    NSString *replyContent;
}
@property (nonatomic, strong) NSArray *replyArray;//评论数组
@property (nonatomic, strong) UIView *replyView;//回复栏
@property (nonatomic, strong) YWHandler *atUser;
@property (nonatomic, strong) UIButton * selectButton;
@property (nonatomic, strong) UITextField * textField;
@property (nonatomic, strong) UIView * line2;
@end

@implementation YWDetectAndUpkeepReplyTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"replyDetail", nil);//@"评论详情";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"observerIcon"] style:UIBarButtonItemStylePlain target:self action:@selector(showObservers:)];
    
    [self setupTableView];
}

- (void)setupTableView{
    [self.tableView registerClass:[YWDetailWorkTableViewCell class] forCellReuseIdentifier:YWDetailWorkTableViewCellIdentifier];
    [self.tableView registerClass:[YWNewCommentCell class] forCellReuseIdentifier:YWNewCommentCellIdetifer];
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.allowsSelection = NO;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    if (self.mission.missionId>0) {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 46, 0);
        [self.navigationController.view addSubview:self.replyView];
    }
}

- (NSArray *)replyArray{
    if (!_replyArray) {
        NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:self.mission.missionId andRelationType:YWReplyRelationTypeDetectAndUpkeep];
        _replyArray = commentArray;
    }
    return _replyArray;
}

#pragma mark - Table view data source
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (indexPath.section == 0) {
//        return [tableView fd_heightForCellWithIdentifier:YWDetailWorkTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWDetailWorkTableViewCell *cell) {
//            cell.maintenanceMission = self.mission;
//        }];
//    }else{
//        return [tableView fd_heightForCellWithIdentifier:YWNewCommentCellIdetifer cacheByIndexPath:indexPath configuration:^(YWNewCommentCell *cell) {
//            [self configureCommentCell:cell atIndexPath:indexPath];
//        }];
//    }
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section == 0 ? 0:1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }  else {
        return self.replyArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YWDetailWorkTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:YWDetailWorkTableViewCellIdentifier];
        cell.maintenanceMission = self.mission;
        return cell;
    } else {
        YWNewCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:YWNewCommentCellIdetifer];
        [self configureCommentCell:cell atIndexPath:indexPath];
        return cell;
    }
}

- (void)configureCommentCell:(YWNewCommentCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    YWReply *reply = self.replyArray[indexPath.row];
    cell.reply = reply;
    //除了第一条评论则隐藏最左边评论图标
    [cell viewWithTag:101 ].hidden = indexPath.row == 0 ? NO : YES;
}

- (UIView *)replyView{
    if (!_replyView) {
        _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-46, SCREEN_WIDTH, 46)];
        _replyView.backgroundColor = [UIColor whiteColor];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        line1.backgroundColor = [UIColor customLineColor];
        [_replyView addSubview:line1];
        [self setReplyViewLayout];
    }
    return _replyView;
}

- (void)setReplyViewLayout{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonW)];
    self.textField.placeholder = NSLocalizedString(@"reply", nil);//@"回复";
    self.textField.font = kContentFont;
    self.textField.returnKeyType = UIReturnKeySend;
    self.textField.delegate = self;
    self.line2 = [[UIView alloc] initWithFrame:CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1)];
    self.line2.backgroundColor = [UIColor customBlueColor];
    
    [_replyView addSubview:self.textField];
    [_replyView addSubview:self.line2];
    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton addTarget:self action:@selector(handleSelectButtonToPeople:) forControlEvents:UIControlEventTouchUpInside];
    [_replyView addSubview:self.selectButton];
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

- (void)handleSelectButtonToPeople:(UIButton *)sende{
    YWSelectAtUserTableViewController * selectAtUserVC = [[YWSelectAtUserTableViewController alloc] init];
    selectAtUserVC.delegate = self;
    NSMutableArray *allUser = [NSMutableArray array];
    //创建人
    if (self.mission.creator) {
        [allUser addObject:self.mission.creator];
    }
    //执行人
    [allUser addObjectsFromArray:self.mission.executors];
    //observer
    [allUser addObjectsFromArray:self.mission.observers];
    selectAtUserVC.allUserArray = allUser;
    [self.navigationController pushViewController:selectAtUserVC animated:YES];
}

- (void)selectAtUser:(YWHandler *)contact{
    if (contact) {
        self.atUser = contact;
        NSString * atButtonTitle = [NSString stringWithFormat:@"@%@",self.atUser.userName.length?self.atUser.userName:@""];
        CGSize size =[atButtonTitle sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGSize standernSize = [[NSString stringWithFormat:@"四个中文字"] sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGFloat width = size.width>standernSize.width ? standernSize.width : size.width;
        width = width + 6;//＋6是让前后有留白，不会紧贴屏幕
        self.selectButton.frame = CGRectMake(0, 0, width, kButtonH);
        self.textField.frame = CGRectMake(width, 0, SCREEN_WIDTH-width-15, kButtonH);
        self.line2.frame = CGRectMake(width, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
        
        self.selectButton.titleLabel.font = KTitleFont;
        [self.selectButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [self.selectButton setTitle:atButtonTitle forState:UIControlStateNormal];
    }else{
        [self whenAtUserIsNilReSetFrame];
    }
}

- (void)whenAtUserIsNilReSetFrame{
    self.atUser = nil;
    self.textField.text = nil;
    self.textField.frame = CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonH);
    self.line2.frame = CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

- (void)addObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:self.mission.observers];
        [tempArray addObject:handler];
        self.mission.observers = [NSArray arrayWithArray:tempArray];
    }
}

- (void)deleteObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[self.mission.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            NSMutableArray *tempArray = [NSMutableArray array];
            [tempArray addObjectsFromArray:self.mission.observers];
            [tempArray removeObject:handler];
            self.mission.observers = [NSArray arrayWithArray:tempArray];
        }
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"writeReplyContent", nil)];
        return NO;
    }else if (textField.text.length > 100){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replyContentLengthCannotMoreThan100", nil)];
        return NO;
    }else if ([YWCommonTool isContainsEmoji:textField.text]){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return NO;
    }
    replyContent = textField.text;
    NSString *url = [YWCommonTool postReplyUrl];
    [[YWReplyManager shareManager] commitReplys:[self createReply] url:url WithComplete:^(BOOL success) {
        if (success) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replySucceed", nil)];
            //回复成功后，要回复原样
            [self whenAtUserIsNilReSetFrame];
            _replyArray = nil;
            [self.tableView reloadData];
        }
    }];
    [textField endEditing:YES];
    return YES;
}

-(YWReply *)createReply{
    YWReply *reply = [[YWReply alloc]init];
    reply.replyId = 0;//提交成功后id会被服务端返回的id替换
    reply.relationId = _mission.missionId;
    reply.relationType = YWReplyRelationTypeDetectAndUpkeep;
    reply.content = replyContent;
    reply.atUser = _atUser;
    YWHandler *replier = [[YWHandler alloc] init];
    replier.uniqueId = [YWLoginTool loginUser].uniqueId;
    reply.replier = replier;
    reply.replyTime = [[NSDate date] timeIntervalSince1970]*1000;
    reply.isRead = YES;
    return reply;
}

- (void)showObservers:(id)sender{
    YWObserverTableViewController *observerVC = [[YWObserverTableViewController alloc] init];
    observerVC.creaters = self.mission.creator?@[self.mission.creator]:nil;
    observerVC.executors = self.mission.executors;
    observerVC.observers = self.mission.observers;
    observerVC.relationId = [@(self.mission.missionId) stringValue];
    observerVC.type = YWReplyRelationTypeDetectAndUpkeep;
    [self.navigationController pushViewController:observerVC animated:YES];
}

#pragma mark ----- 有关键盘
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.replyView.hidden = YES;
    [self.textField endEditing:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.replyView.hidden = NO;
    [self setUpNotification];
}

- (void)setUpNotification{
    //    键盘show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //    键盘hide
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addObserver:) name:KPostMissionAddObserverNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteObserver:) name:KPostMissionDeleteObserverNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)info{
    //键盘高度
    CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    // 取得键盘的动画时间
    CGFloat duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 46 - kbHeight;
    }];
}

- (void)keyboardWillHide:(NSNotification *)info{
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 46;
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.navigationController.view endEditing:YES];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
